package com.nimbusung.domain;

import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.preference.PreferenceManager;
import android.text.Html;
import android.text.Html.ImageGetter;
import android.text.Spanned;
import android.text.method.LinkMovementMethod;
import android.view.View;
import android.view.ViewGroup;
import android.view.LayoutInflater;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.BaseExpandableListAdapter;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;

import javax.swing.plaf.metal.MetalIconFactory.FolderIcon16;

import com.nimbusung.R;


/**
 * This is a adapter which creates the newslist. 
 * The list is build as a tree with parents as headlines and 
 * children to the parents as the related news. 
 * (Possible for a parent to have many children)  
 * 
 * Also parse html-contents from the children. 
 * 
 * 
 * @Author Anton Karlsson 
 *
 */
public class MessageListAdapter extends BaseExpandableListAdapter implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = -5138560828307686539L;
	//private Context context;
	private ArrayList<NewsRow> groups;
	private ArrayList<ArrayList<String>> messages;
	private LayoutInflater inflater;
	private static Context context;
	private String textSizeChild = "14";

	public MessageListAdapter(Context context, ArrayList<NewsRow> groups,  ArrayList<ArrayList<String>> messages ) { 
		//this.context = context;
		this.groups = groups;
		this.messages = messages;
		this.inflater = LayoutInflater.from( context );
		this.context = context;
		
		setup();
	}
	
	public void setup(){
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
		textSizeChild = prefs.getString("textsizenews", "14");
	}

	public Object getChild(int groupPosition, int childPosition) {
		return messages.get( groupPosition ).get( childPosition );
	}

	public long getChildId(int groupPosition, int childPosition) {
		return (long)( groupPosition*1024+childPosition );  // Max 1024 children per group
	}

	public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {

		View v = null;

		if( convertView != null )
			v = convertView;
		else
			v = inflater.inflate(R.layout.news_child_row, parent, false); 
		String c = (String)getChild( groupPosition, childPosition );
		TextView messagePlace = (TextView)v.findViewById( R.id.childname );

		if( messagePlace != null ){

			Spanned s = Html.fromHtml(c, new ImageGetter() {

				public Drawable getDrawable(String source) {                  
					Drawable d = null;
					try {
						InputStream src = imageFetch(source);
						d = Drawable.createFromStream(src, "src");
						if(d != null){
							d.setBounds(0,0,d.getIntrinsicWidth(),
									d.getIntrinsicHeight());
						}
					} catch (MalformedURLException e) {
						e.printStackTrace(); 
					} catch (IOException e) {
						e.printStackTrace();  
					}

					return d;
				}

			},null);

			messagePlace.setClickable(true);

			messagePlace.setMovementMethod(LinkMovementMethod.getInstance());
			messagePlace.setTextSize(Float.parseFloat(textSizeChild));
			messagePlace.setText(s);
			v.setBackgroundColor(0xCFCFCF);

		} 
		return v;
	}

	public InputStream imageFetch(String source) throws MalformedURLException,IOException {
		URL url = new URL(source);
		Object o = url.getContent();
		InputStream content = (InputStream)o;
		// add delay here...     
		return content;
	}

	public int getChildrenCount(int groupPosition) {
		return messages.get( groupPosition ).size();
	}

	public Object getGroup(int groupPosition) {
		return groups.get( groupPosition );        
	}

	public int getGroupCount() {
		return groups.size();
	}

	public long getGroupId(int groupPosition) {
		return (long)( groupPosition*1024 );  // To be consistent with getChildId
	} 

	public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
		
		View v = null;
		if( convertView != null )
			v = convertView;
		else
			v = inflater.inflate(R.layout.news_group_row, parent, false); 
		
		NewsRow newsRow = (NewsRow)getGroup( groupPosition );
		
		TextView newsTitle  = (TextView)v.findViewById( R.id.title );
		TextView churchName = (TextView)v.findViewById( R.id.churchname );
		TextView pubDate    = (TextView)v.findViewById( R.id.pubDate );
		ImageView image     = (ImageView)v.findViewById( R.id.imageChurchView);
		ImageView arrow     = (ImageView)v.findViewById(R.id.group_arrow);
		
		if( newsRow != null ){
			
			//Set Church
			churchName.setText( newsRow.getChurch() );
		
			//Set Title
			newsTitle.setText( newsRow.getTitle() );
			//newsTitle.setTextColor(Color.BLUE);
			
			//Set Image
			if(newsRow.getChurch().compareTo("Nimbus") == 0) {
				image.setImageResource(R.drawable.ung);
			} else if(newsRow.getChurch().compareTo("Filadelfia") == 0){
				image.setImageResource(R.drawable.youth);
			}
			
			//Set Date
			pubDate.setText( newsRow.getTime());
		}
		
		if(isExpanded){
			arrow.setImageResource(R.drawable.arrow_down);
			newsTitle.setText("");
		}else{
			arrow.setImageResource(R.drawable.arrow_left);
			newsTitle.setText( newsRow.getTitle());
		}
		
		return v;
	}

	public boolean hasStableIds() {
		return true;
	}

	public boolean isChildSelectable(int groupPosition, int childPosition) {
		return true;
	} 

	public void onGroupCollapsed (int groupPosition) {} 
	public void onGroupExpanded(int groupPosition) {}
	
	
	//TODO: Remove
	public void save(){
		FileOutputStream fos;
		try {
			fos = context.openFileOutput("MESSAGELIST", Context.MODE_PRIVATE);
			ObjectOutputStream os = new ObjectOutputStream(fos);
			os.writeObject(this);
			os.close();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public static MessageListAdapter load(){
		FileInputStream fis;
		MessageListAdapter objClass = null;
		try {
			fis = context.openFileInput("MESSAGELIST");
			ObjectInputStream is = new ObjectInputStream(fis);
			objClass = (MessageListAdapter) is.readObject();
			is.close();
					
		} catch (Exception e) {
			e.printStackTrace();
		}
		return objClass;
	}


}
